package io.renren.modules.aic.service.impl;

import io.renren.common.utils.DecimalUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.ProjectConstant;
import io.renren.common.utils.Query;
import io.renren.common.validator.Assert;
import io.renren.modules.aic.dao.CtocTransactionDao;
import io.renren.modules.aic.entity.BalanceDetailEntity;
import io.renren.modules.aic.entity.CtocOrderEntity;
import io.renren.modules.aic.entity.CtocTransactionEntity;
import io.renren.modules.aic.entity.MemberEntity;
import io.renren.modules.aic.service.BalanceDetailService;
import io.renren.modules.aic.service.CtocOrderService;
import io.renren.modules.aic.service.CtocTransactionService;
import io.renren.modules.aic.service.MemberService;

import java.util.Date;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

@Service("ctocTransactionService")
public class CtocTransactionServiceImpl extends ServiceImpl<CtocTransactionDao, CtocTransactionEntity> implements CtocTransactionService {

	@Autowired
	CtocTransactionDao ctocTransactionDao;

	@Autowired
	MemberService memberService;

	@Autowired
	BalanceDetailService balanceDetailService;

	@Autowired
	CtocOrderService ctocOrderService;

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		String mobile = (String) params.get("mobile");
		String orderNo = (String) params.get("orderNo");
		Page<CtocTransactionEntity> page = this.selectPage(
				new Query<CtocTransactionEntity>(params).getPage(),
				new EntityWrapper<CtocTransactionEntity>().eq(StringUtils.isNotBlank(orderNo), "order_no", orderNo).andNew(StringUtils.isNotBlank(mobile),
						"buyer_mobile={0} or seller_mobile={1}", mobile, mobile));

		return new PageUtils(page);
	}

	@Override
	public Double totalAmount(Date d) {
		Double value = ctocTransactionDao.totalAmount(d);
		return value == null ? 0 : value;
	}

	@Override
	public Double totalCoinAmount(Date d) {
		Double value = ctocTransactionDao.totalCoinAmount(d);
		return value == null ? 0 : value;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void sellerConfirm(Long[] ids) {
		for (Long transId : ids) {

			CtocTransactionEntity ctocTransaction = this.selectById(transId);
			Assert.notNull(ctocTransaction, "交易不存在");
			if (ctocTransaction.getStatus() != ProjectConstant.CTOC_TRANS_STATUS_PAID) {
				System.out.println(ctocTransaction.getOrderNo() + ":当前交易状态不可确认收款,已跳过处理");
				continue;
			}

			MemberEntity seller = memberService.selectById(ctocTransaction.getSellerMemberId());

			Date now = new Date();

			// 更新会员余额
			double blocked = DecimalUtils.add(ctocTransaction.getCoinQuantity(), ctocTransaction.getTransFee());// 总币+手续费
			seller.setBlockedBalance(DecimalUtils.sub(seller.getBlockedBalance(), blocked));
			seller.setUpdateTime(now);
			memberService.updateById(seller);
			MemberEntity buyer = memberService.selectById(ctocTransaction.getBuyerMemberId());
			buyer.setBalance(DecimalUtils.add(buyer.getBalance(), ctocTransaction.getCoinQuantity()));// 余额+买入的币
			buyer.setUpdateTime(now);
			memberService.updateById(buyer);

			// 插入卖家资金流水
			BalanceDetailEntity bd = new BalanceDetailEntity();
			bd.setBalanceChange(DecimalUtils.sub(0, blocked));
			bd.setMemberId(seller.getId());
			bd.setCategory(1);// 卖出
			bd.setCreateTime(now);
			balanceDetailService.insert(bd);

			// 插入买家资金流水
			bd = new BalanceDetailEntity();
			bd.setBalanceChange(ctocTransaction.getCoinQuantity().doubleValue());
			bd.setMemberId(buyer.getId());
			bd.setCategory(0);// 买入
			bd.setCreateTime(now);
			balanceDetailService.insert(bd);

			// 更新挂单状态
			CtocOrderEntity ctocOrder = ctocOrderService.selectOne(new EntityWrapper<CtocOrderEntity>().eq("member_id", ctocTransaction.getBuyerMemberId()).eq("order_no",
					ctocTransaction.getOrderNo()));
			ctocOrder.setUpdateTime(now);
			ctocOrder.setStatus(ProjectConstant.CTOC_ORDER_STATUS_FINISH);
			ctocOrderService.updateById(ctocOrder);

			// 更新订单状态
			ctocTransaction.setUpdateTime(now);
			ctocTransaction.setFinishTime(now);
			ctocTransaction.setStatus(ProjectConstant.CTOC_TRANS_STATUS_CONFIRMED);
			this.updateById(ctocTransaction);
		}
	}
}
